package com.lin.servicecmn.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lin.servicecmn.listener.DictListener;
import com.lin.servicecmn.mapper.DictMapper;
import com.lin.servicecmn.service.DictService;
import lin.yygh.model.cmn.Dict;
import lin.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

//    @Autowired
//    DictMapper dictMapper;

    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);

//        List<Dict> list = baseMapper.selectList(wrapper);
//
//        //向list集合每隔dict对象中设置hasChildren
//        for (Dict dict : list) {
//            dict.setHasChildren(this.isChildren(dict.getId()));
//        }

        List<Dict> list = baseMapper.selectList(wrapper).stream().
                map((item) -> {
                    item.setHasChildren(this.isChildren(item.getId()));
                    return item;
                }).collect(Collectors.toList());

        return list;

    }

    //判断id下面是否有子节点

    private boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        if (count>0){
            return true;
        }
        return false;
    }

    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置ContentType类型
        response.setContentType("application/vnd.ms-excel");
        //设置编码
        response.setCharacterEncoding("utf-8");

        String fileName = "dict";
        //设置头信息，让这个操作以下载方式打开
        response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");

        //查询数据库
//        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictEeVoList = new ArrayList<>();

        baseMapper.selectList(null).stream().
                map((item) -> {
                    DictEeVo dictEeVo = new DictEeVo();
                    BeanUtils.copyProperties(item, dictEeVo);
                    dictEeVoList.add(dictEeVo);
                    return dictEeVo;
                }).collect(Collectors.toList());


        //把Dict 转换成 DictEeVo
//        for (Dict dict : dictList) {
//            DictEeVo dictEeVo = new DictEeVo();
//            BeanUtils.copyProperties(dict,dictEeVo);
//            dictEeVoList.add(dictEeVo);
//        }

        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(dictEeVoList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictcode, String value) {

//        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
//
//        wrapper.eq("value",value);
//
//        //如果dictcode为空，就直接根据value进行查询
//        if (!StringUtils.isEmpty(dictcode)){
//            wrapper.eq("dict_code",dictcode);
//        }
//
//        Dict dict = baseMapper.selectOne(wrapper);
//
////        Long parentId = dict.getId();
////
////        baseMapper
//
//        return dict.getName();

        if (StringUtils.isEmpty(dictcode)){
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else{
            Dict dictCode = this.getDictByDictCode(dictcode);
            Long parent_id = dictCode.getId();
            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)
                    .eq("value", value));
            return finalDict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code ",dictCode);
        Dict dict = baseMapper.selectOne(wrapper);

        Long parent_id= dict.getId();
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",parent_id);
        List<Dict> dictList = baseMapper.selectList(queryWrapper);
        return dictList;
    }

    private Dict getDictByDictCode(String dictcode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictcode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

}
